import React, { useEffect, useRef } from 'react';
import { Collapse, List, Spin, Button, Tooltip, Dropdown } from 'antd';
import { PlusOutlined, FolderAddOutlined, DownOutlined, ImportOutlined, FileAddOutlined } from '@ant-design/icons';

interface DGroup {
    id: string;
    title: string;
    baseId: string;
    sortOrder: number;
}

interface Document {
    id: string;
    groupId: string;
    baseId: string;
    content: string;
    title?: string;
    sortOrder: number;
}

interface GroupSidebarProps {
    groups: DGroup[];
    docs: Record<string, Document[]>;
    activeGroup: string | null;
    activeDoc: Document | null;
    loadingMore: boolean;
    pagination: {
        current: number;
        pageSize: number;
        total: number;
        hasMore: boolean;
    };
    onGroupChange: (groupId: string) => void;
    onDocClick: (doc: Document) => void;
    onAddGroup: () => void;
    onAddDocument: () => void;
    onImportDocument: () => void;
    onLoadMore: () => void;
}

const GroupSidebar: React.FC<GroupSidebarProps> = ({
    groups,
    docs,
    activeGroup,
    activeDoc,
    loadingMore,
    pagination,
    onGroupChange,
    onDocClick,
    onAddGroup,
    onAddDocument,
    onImportDocument,
    onLoadMore
}) => {
    const groupsContainerRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        const container = groupsContainerRef.current;
        if (!container) return;

        const handleScroll = () => {
            if (!pagination.hasMore || loadingMore) return;
            const { scrollTop, scrollHeight, clientHeight } = container;
            const isBottom = scrollTop + clientHeight >= scrollHeight - 50;
            if (isBottom) onLoadMore();
        };

        container.addEventListener('scroll', handleScroll);
        return () => container.removeEventListener('scroll', handleScroll);
    }, [pagination, loadingMore, onLoadMore]);

    return (
        <div
            ref={groupsContainerRef}
            style={{
                width: '100%',
                height: '100%',
                background: '#fff',
                borderRight: '1px solid #eee',
                overflowY: 'auto',
                display: 'flex',
                flexDirection: 'column'
            }}
        >
            <div style={{
                padding: '12px 16px',
                borderBottom: '1px solid #eee',
                display: 'flex',
                justifyContent: 'flex-end'
            }}>
                <Tooltip title="添加文档分组">
                    <Button
                        type="primary"
                        icon={<FolderAddOutlined />}
                        onClick={onAddGroup}
                    >
                        分组
                    </Button>
                </Tooltip>
            </div>

            {groups.length === 0 ? (
                <div style={{ padding: 16, textAlign: 'center', flex: 1 }}>
                    <Spin tip="加载分组中..." />
                </div>
            ) : (
                <div style={{ flex: 1, overflowY: 'auto' }}>
                    <Collapse
                        accordion
                        onChange={(key) => {
                            if (Array.isArray(key)) {
                                if (key.length > 0) onGroupChange(key[0]);
                            } else {
                                onGroupChange(key);
                            }
                        }}
                        style={{ border: 'none' }}
                    >
                        {groups.map(group => (
                            <Collapse.Panel
                                header={group.title}
                                key={group.id}
                                extra={
                                    <Dropdown
                                        menu={{
                                            items: [
                                                {
                                                    key: 'create',
                                                    icon: <FileAddOutlined />,
                                                    label: '新建文档',
                                                    onClick: () => {
                                                        onGroupChange(group.id);
                                                        onAddDocument();
                                                    }
                                                },
                                                {
                                                    key: 'import',
                                                    icon: <ImportOutlined />,
                                                    label: '导入文档',
                                                    onClick: () => {
                                                        onGroupChange(group.id);
                                                        onImportDocument();
                                                    }
                                                }
                                            ]
                                        }}
                                        trigger={['click']}
                                        placement="bottomRight"
                                    >
                                        <Button
                                            type="text"
                                            icon={<PlusOutlined />}
                                            size="small"
                                            onClick={(e) => {
                                                e.stopPropagation();
                                            }}
                                        />
                                    </Dropdown>
                                }
                            >
                                <List
                                    dataSource={docs[group.id] || []}
                                    renderItem={(item: Document) => (
                                        <List.Item
                                            style={{
                                                cursor: 'pointer',
                                                color: activeDoc?.id === item.id ? '#1677ff' : undefined
                                            }}
                                            onClick={() => onDocClick(item)}
                                        >
                                            {item.title || `文档_${item.id?.slice(-4) || '新文档'}`}
                                        </List.Item>
                                    )}
                                />
                            </Collapse.Panel>
                        ))}
                    </Collapse>

                    <div style={{ padding: '16px', textAlign: 'center' }}>
                        {loadingMore ? (
                            <Spin tip="加载更多分组..." />
                        ) : pagination.hasMore ? (
                            <Button
                                type="dashed"
                                onClick={onLoadMore}
                                icon={<DownOutlined />}
                                block
                            >
                                加载更多
                            </Button>
                        ) : (
                            <div style={{ color: '#999', padding: '8px' }}>
                                没有更多分组了
                            </div>
                        )}
                    </div>
                </div>
            )}
        </div>
    );
};

export default GroupSidebar;